// src/app/workspace/[workspaceId]/member/[memberId]/page.tsx
'use client';
import React, {useEffect, useState} from 'react';
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {useMemberId} from "@/hooks/social/use-member-id";
import {useCreateOrGetConversation} from "@/features/conversations/api/use-create-or-get-conversation";
import {useCurrentMember} from "@/features/workspaces/api/use-current-member";
import {AlertTriangle, Loader} from "lucide-react";
import {toast} from "sonner";
import Conversation from "@/app/social/workspace/[workspaceId]/member/[memberId]/_components/conversation";
import {useCurrentUser} from "@/hooks/use-current-user";

// 强制每个请求动态渲染
export const dynamic = 'force-dynamic'

// 1v1对话
const Page = () => {
    const user = useCurrentUser()

    const workspaceId = useWorkspaceId()
    // 当前对话的用户的id
    const memberId = useMemberId()

    const {data, isPending, mutate} = useCreateOrGetConversation()
    const [conversationId, setConversationId] = useState<string>();

    useEffect(() => {
        (async () => {
            const {data, isLoading} = await useCurrentMember({
                workspaceId, userId: user?.id!
            })
            await mutate({workspaceId, memberId, curMemberId: data.id}, {
                onSuccess(id: string) {
                    setConversationId(id)
                },
                onError() {
                    toast.error(`Failed to create or get conversation`)
                }
            })
        })()
    }, [memberId, workspaceId]);

    if (isPending)
        return <div className={`h-full flex-1 flex items-center
            justify-center flex-col gap-2`}>
            <Loader className={`size-5 animate-spin text-muted-foreground`}/>
        </div>

    if (!data || !conversationId)
        return <div className={`flex flex-col gap-y-2 h-full items-center justify-center`}>
            <AlertTriangle className={`size-5 text-muted-foreground`}/>
            <span className={`text-sm text-muted-foreground`}>Conversation not found</span>
        </div>

    return (
        <>
            <Conversation
                id={conversationId}
                // data={data}
            />
        </>
    );
};

export default Page;